package com.byxy.computer.student.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.byxy.computer.student.entity.HomeWork;
import com.byxy.computer.student.entity.LessonMaterial;
import com.byxy.computer.student.entity.Student;
import com.byxy.computer.student.json.AjaxEasyUIPage;
import com.byxy.computer.student.json.AjaxObject;
import com.byxy.computer.student.service.HomeWorkService;
import com.byxy.computer.student.service.LessonMaterialService;
import com.byxy.computer.student.service.StudentService;
import com.byxy.computer.student.utils.ZipUtil;
import com.byxy.computer.utils.excel.ExportExcel;
import com.byxy.computer.utils.excel.ImportExcel;

@Controller
@RequestMapping("html5/teacher")
public class Html5TeacherController {

	@Autowired
	private StudentService studentService;
	@Autowired
	private LessonMaterialService lessonMaterialService;
	@Autowired
	private HomeWorkService homeWorkService;

	// 学生分页
	@RequestMapping(value = "list_json.do", method = RequestMethod.GET)
	@ResponseBody
	public AjaxEasyUIPage getJson(int page, int rows, String sort, String order, HttpSession session) {
		AjaxEasyUIPage ajax = studentService.getJson(page, rows, sort, order);
		session.setAttribute("total", ajax.getTotal());

		return ajax;
		// return ajaxEasyUIPage;
	}

	// 删除所有学生数据
	@RequestMapping(value = "deleteAll", method = RequestMethod.GET)
	@ResponseBody
	public AjaxObject deleteAll() {
		studentService.deleteAll();
		AjaxObject ajax = new AjaxObject(AjaxObject.OK);
		return ajax;
	}
	// 删除上节课数据
		@RequestMapping(value = "deleteOld", method = RequestMethod.GET)
		@ResponseBody
		public void deleteOld() {
			List<Student> stus=new ArrayList<Student>();
			for(Student stu:studentService.listAll()){
				stu.setFilesize(null);
				stu.setGood(null);
				stu.setHomework(null);
				stu.setStats(null);
				stu.setComputername(null);
				stus.add(stu);
			}
			studentService.save(stus);
		}
	// 导入学生数据
	@RequestMapping(value = "upload_json", method = RequestMethod.POST)
	@ResponseBody
	public AjaxObject upload_json(MultipartFile attach)
			throws InvalidFormatException, IOException, InstantiationException, IllegalAccessException {
		ImportExcel imp = new ImportExcel(attach, 0, 0);
		List<Student> stds = imp.getDataList(Student.class, null);
		studentService.save(stds);
		AjaxObject ajax = new AjaxObject(AjaxObject.OK);
		return ajax;
	}

	// 导出数据模板
	@RequestMapping(value = "exportemp", method = RequestMethod.GET)
	@ResponseBody
	public AjaxObject exportemp(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String excelTitle = Student.class.getSimpleName();
		AjaxObject ajax = new AjaxObject(AjaxObject.OK);
		List<Student> records = new ArrayList<Student>();
		Student s = new Student("18216044344", "王小明");
		records.add(s);
		String fileName = excelTitle + ".xls";
		new ExportExcel(null, Student.class).setDataList(records).write(response, fileName).dispose();
		return ajax;
	}

	// 导出学生数据
	@RequestMapping(value = "exportxls", method = RequestMethod.GET)
	@ResponseBody
	public AjaxObject exportxls(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String excelTitle = DateFormat.getDateInstance().format(new Date()) + "_Attendance";// Student.class.getSimpleName();
		List<Student> records = studentService.listAll();
		AjaxObject ajax = new AjaxObject(AjaxObject.OK);
		String fileName = excelTitle + ".xls";
		new ExportExcel(null, Student.class).setDataList(records).write(response, fileName).dispose();
		return ajax;
	}

	// 上传上课资料
	@RequestMapping(value = "uploadMaterial", method = RequestMethod.POST)
	@ResponseBody
	public AjaxObject upload(@RequestParam("attachs") MultipartFile[] attachs, HttpServletRequest req) {
		String strDate = "Material";// DateFormat.getDateInstance(DateFormat.SHORT).format(new
		AjaxObject ajax = new AjaxObject(AjaxObject.OK); // Date());
		String path = "/upload/" + strDate;
		String realpath = req.getSession().getServletContext().getRealPath(path);
		for (MultipartFile attach : attachs) {
			if (attach.isEmpty())
				continue;
			File f = new File(realpath + "/" + attach.getOriginalFilename());
			try {
				lessonMaterialService.save(
						new LessonMaterial(attach.getOriginalFilename(), strDate + "/" + attach.getOriginalFilename()));
				FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ajax;
	}

	// 获取任务书
	@RequestMapping(value = "getfiles.do", method = RequestMethod.GET)
	@ResponseBody
	public List<LessonMaterial> getfiles() {
		List<LessonMaterial> getfiles = lessonMaterialService.listAll();
		return getfiles;
	}

	// 点赞
	@RequestMapping(value = "good", method = RequestMethod.GET)
	@ResponseBody
	public AjaxObject good(String uid) {
		AjaxObject ajax = new AjaxObject(AjaxObject.OK);
		studentService.sayGood(new Student(uid, ""));
		return ajax;
	}

	// 批评
	@RequestMapping(value = "bad", method = RequestMethod.GET)
	@ResponseBody
	public AjaxObject bad(String uid) {
		AjaxObject ajax = new AjaxObject(AjaxObject.OK);
		studentService.sayBad(new Student(uid, ""));
		return ajax;
	}

	// 清除点名数据
	@RequestMapping(value = "delete", method = RequestMethod.GET)
	@ResponseBody
	public String delete(String uid) {
		studentService.resetLesson(new Student(uid, ""));
		return "redirect:list";
	}

	// 旷课
	@RequestMapping(value = "truant", method = RequestMethod.GET)
	@ResponseBody
	public AjaxObject truant(String uid) {
		AjaxObject ajax = new AjaxObject(AjaxObject.OK);
		studentService.playTruant(new Student(uid, ""));
		return ajax;
	}

	// 迟到
	@RequestMapping(value = "late", method = RequestMethod.GET)
	@ResponseBody
	public AjaxObject late(String uid) {
		AjaxObject ajax = new AjaxObject(AjaxObject.OK);
		studentService.beLate(new Student(uid, ""));
		return ajax;
	}

	// 病假
	@RequestMapping(value = "sick", method = RequestMethod.GET)
	@ResponseBody
	public AjaxObject sick(String uid) {
		AjaxObject ajax = new AjaxObject(AjaxObject.OK);
		studentService.sick(new Student(uid, ""));
		return ajax;
	}

	// 事假
	@RequestMapping(value = "holiday", method = RequestMethod.GET)
	@ResponseBody
	public AjaxObject holiday(String uid) {
		AjaxObject ajax = new AjaxObject(AjaxObject.OK);
		studentService.holiday(new Student(uid, ""));
		return ajax;
	}

	@RequestMapping(value = "get", method = RequestMethod.GET)
	@ResponseBody
	public AjaxEasyUIPage get() {
		AjaxEasyUIPage ajax = new AjaxEasyUIPage();
		return ajax;
	}

	// 下载学生的作业
	@RequestMapping("downloadzip2")
	public void downloadFile2(HttpServletRequest request, HttpServletResponse response) {
		String strDate = DateFormat.getDateInstance().format(new Date());
		String path = "/upload/" + strDate;
		String realpath = request.getSession().getServletContext().getRealPath(path);
		File f = new File(realpath);
		if(!f.exists()){
			f.mkdirs();
		}
		try {
			String realname = URLEncoder.encode(strDate, "utf-8");
			response.reset();
			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;fileName=" + realname + ".zip");
			OutputStream os = response.getOutputStream();
			ZipOutputStream zipOut = new ZipOutputStream(os,Charset.forName("GBK"));
			ZipUtil.zipFiles(realpath, zipOut);
			zipOut.close();
			os.close();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 获取的作业列表
	@RequestMapping(value = "getwork.do", method = RequestMethod.GET)
	@ResponseBody
	public List<HomeWork> getWork(String uid) {
		return homeWorkService.findByUId(uid);
	}

	// 事假
	@RequestMapping(value = "delMeterial", method = RequestMethod.GET)
	@ResponseBody
	public AjaxObject delMeterial(String id, HttpServletRequest req) {
		AjaxObject ajax = new AjaxObject(AjaxObject.OK);
		LessonMaterial l = lessonMaterialService.findById(id);
		String path = "/upload";
		String pathfile = req.getSession().getServletContext().getRealPath(path);
		pathfile = pathfile + "/" + l.getUrl();
		File file = new File(pathfile);
		if (file.exists() && file.isFile()) {
			file.delete();
		}
		lessonMaterialService.deleteById(id);
		return ajax;
	}

	@RequestMapping(value = "getCount.do", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Integer> getCount() {
		Map<String, Integer> count = new HashMap<String, Integer>();
		int arrive = studentService.getArrive();
		int work = studentService.getHomeWork();
		count.put("arrive", arrive);
		count.put("work", work);
		return count;
	}

	@RequestMapping(value = "getUrl.do", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getUrl(HttpServletRequest request) throws UnknownHostException {
		Map<String, Object> u = new HashMap<String, Object>();
		InetAddress addr=InetAddress.getLocalHost();
		String ip = addr.getHostAddress();
		 String url = "";
		  url = request.getScheme() + "://" + ip+ ":" + request.getServerPort()
			+ request.getContextPath();
		  	u.put("url", url);
		return u;
	}
	
	@ResponseBody
	@RequestMapping(value = "dologin.do", method = RequestMethod.POST)
	public AjaxObject login(String username, String password, HttpServletRequest req) {
		AjaxObject ajax = new AjaxObject();
		req.getSession().removeAttribute("admin");
		if ("admin".equals(username) && "admin".equals(password)) {
			ajax.setResult(AjaxObject.OK);
			req.getSession().setAttribute("admin", "admin");
		} else {
			ajax.setResult(AjaxObject.ERROR);
			ajax.setMsg("用户名与密码不正确。");
		}
		return ajax;
	}
	
	// 作业列表
		@ResponseBody
		@RequestMapping(value = "download.do", method = RequestMethod.GET)
		public AjaxObject downloadMaterial(String id, HttpServletRequest request) {
			AjaxObject ajax = new AjaxObject();
			LessonMaterial l = lessonMaterialService.findById(id);
			if (l != null) {
				ajax.setResult(AjaxObject.OK);
				String ctx = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
						+ request.getContextPath() + "/upload/" + l.getUrl();
				ajax.setMsg(ctx);
			} else {
				ajax.setResult(AjaxObject.ERROR);
				ajax.setMsg("找不到资料文件，该文件可以已经删除了");
			}
			return ajax;
		}
		//获取到文件地址用流下载
		@ResponseBody
		@RequestMapping(value = "downloadByIo", method = RequestMethod.GET)
		public void xz(String url, HttpServletRequest request,HttpServletResponse response){
			String realpath = request.getSession().getServletContext().getRealPath("/");
			int len = url.lastIndexOf("/");
			if (len > 0) {
				String name = url.substring(len + 1);
				File file = new File(realpath + "/upload/Material/" + name);
				if (file.exists()) {
					try {
						String realname = new String(name.getBytes("gbk"), "ISO-8859-1");
						response.reset();
						response.setCharacterEncoding("utf-8");
//						response.setContentType("multipart/form-data");
						response.setContentType("application/x-msdownload");
						response.setHeader("Content-Disposition", "attachment;fileName=" + realname);
						InputStream inputStream = new FileInputStream(file);
						int fileLength = (int) file.length();
						response.setContentLength(fileLength);
						OutputStream os = response.getOutputStream();
						byte[] b = new byte[2048];
						int length;
						while ((length = inputStream.read(b)) > 0) {
							os.write(b, 0, length);
						}
						inputStream.close();
						os.close();
					} catch (UnsupportedEncodingException e1) {
						e1.printStackTrace();
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			
			
		}
		// 作业列表
	@ResponseBody
	@RequestMapping(value = "downloadHomeWork.do", method = RequestMethod.GET)
	public AjaxObject downloadHomeWork(String id, HttpServletRequest request) {
		AjaxObject ajax = new AjaxObject();
		HomeWork l = homeWorkService.findById(id);
		if (l != null) {
			ajax.setResult(AjaxObject.OK);
			String ctx = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath() + "/upload/" +l.getFilePath();
			ajax.setMsg(ctx);
		} else {
			ajax.setResult(AjaxObject.ERROR);
			ajax.setMsg("找不到资料文件，该文件可以已经删除了");
		}
		return ajax;
	}
}
